package com.htn.common.core.base;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author hongfei
 */
@Slf4j
public class CompositeRequestReceiver extends HashMap<String, Object> {
    private static final long serialVersionUID = 6244068544312417745L;

    private JSONObject innerJSON;

    public CompositeRequestReceiver(){
        super();
        innerJSON = JSONUtil.parseFromMap(this);
    }

    public CompositeRequestReceiver(String strJSON){
        super();
        try{
            innerJSON = JSONUtil.parseObj(strJSON);
            this.putAll(innerJSON);
        }catch(Exception e){
            innerJSON = JSONUtil.parseFromMap(this);
        }
    }


    @Override
    public Object put(String key, Object value) {
        Object obj = super.put(key, value);
        innerJSON.put(key, value);
        return obj;
    }


    @Override
    public void putAll(Map<? extends String, ?> m) {
        super.putAll(m);
        for(Entry<? extends String, ?> en : m.entrySet()){
            innerJSON.put(en.getKey(), en.getValue());
        }
    }

    @Override
    public Object remove(Object key) {
        Object obj = super.remove(key);
        innerJSON.remove(key.toString());
        return obj;
    }

    public <T> T getModel(String propName, Class<T> clazz){
        try {
            JSONObject jsonPart = innerJSON.getJSONObject(propName);
            return JSONUtil.toBean(jsonPart, clazz, true);
        }catch(Exception e){
            log.warn("[CompositeRequestReceiver]getModel error", e);
            return null;
        }
    }

    public <T> T getModel(Class<T> clazz){
        try {
            JSONObject jsonPart = innerJSON;
            return JSONUtil.toBean(jsonPart, clazz, true);
        }catch(Exception e){
            log.warn("[CompositeRequestReceiver]getModel error", e);
            return null;
        }
    }

    public <T> List<T> getModels(String propName, Class<T> clazz){
        try {
            JSONArray jsonPart = innerJSON.getJSONArray(propName);
            return JSONUtil.toList(jsonPart, clazz);
        }catch(Exception e){
            log.warn("[CompositeRequestReceiver]getModels error", e);
            return null;
        }
    }

    @Override
    public String toString() {
        return innerJSON.toString();
    }

    public String getStr(String key){
        return innerJSON.getStr(key);
    }

}
